﻿using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using Resources;
using ud_SwirlingQuestion.Business;
using System.Collections.Generic;

namespace ud_SwirlingQuestion
{
    public partial class SwirlingQuestionList : UserControl
    {
        #region Properties

        private int pageNumber = 1;
        private int totalPages = 1;
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string EditAltText = "Edit";
        protected Double TimeOffset;
        private TimeZoneInfo timeZone;
        protected DateTime CalendarDate;
        protected bool ShowGoogleMap = true;
        protected string FeedBackLabel = string.Empty;
        protected string GmapApiKey = string.Empty;
        protected bool EnableContentRating;
        protected string IntenseDebateAccountId = string.Empty;
        protected bool ShowCommentCounts = true;
        protected string EditLinkText = SwirlingQuestionResource.EditLink;
        protected string EditLinkTooltip = SwirlingQuestionResource.EditLink;
        protected string EditLinkImageUrl = string.Empty;
        private mojoBasePage basePage;
        protected SwirlingQuestionConfiguration config = new SwirlingQuestionConfiguration();

        private int pageId = -1;
        private int moduleId = -1;
        private string siteRoot = string.Empty;
        private string imageSiteRoot = string.Empty;
        private readonly DBSwirlingQuestion repository = new DBSwirlingQuestion();
        private List<ud_QA> listQuestion = new List<ud_QA>();

        public int PageId
        {
            get { return pageId; }
            set { pageId = value; }
        }

        public int ModuleId
        {
            get { return moduleId; }
            set { moduleId = value; }
        }

        public string SiteRoot
        {
            get { return siteRoot; }
            set { siteRoot = value; }
        }

        public string ImageSiteRoot
        {
            get { return imageSiteRoot; }
            set { imageSiteRoot = value; }
        }

        public SwirlingQuestionConfiguration Config
        {
            get { return config; }
            set { config = value; }
        }

        public bool IsEditable { get; set; }

        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            gvOthersArticle.PageIndexChanging += gvOthersArticle_PageIndexChanging;
            SetJQueryScript();
        }

       
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;
            LoadSettings();
            PopulateLabels();
            PopulateControls();
        }

        private void PopulateControls()
        {
            BindQuestion();
            PopulateOtherArticles();
        }

        private void PopulateOtherArticles()
        {
            if (config.ShowOthers && !config.UsePaging)
            {
                List<ud_QA> others = repository.GetAllPublished(moduleId);
                if (others.Count <= config.PageSize)
                {
                    pnlOthersArticle.Visible = false;
                    return;
                }
                others.RemoveRange(0, config.PageSize);
                gvOthersArticle.DataSource = others;
                gvOthersArticle.DataBind();
                gvOthersArticle.AllowPaging = config.OthersPageSize < others.Count;
            }
            else
            {
                pnlOthersArticle.Visible = false;
            }
        }

        void gvOthersArticle_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvOthersArticle.PageIndex = e.NewPageIndex;
            PopulateOtherArticles();
        }

        private void BindQuestion()
        {
            listQuestion = repository.GetPage(moduleId, config.PageSize, pageNumber, out totalPages);
            lvQA.DataSource = listQuestion;
            lvQA.DataBind();
            string pageUrl = SiteRoot + "/SwirlingQuestion/ViewList.aspx"
                   + "?pageid=" + pageId.ToInvariantString()
                   + "&amp;mid=" + moduleId.ToInvariantString()
                   + "&amp;pagenumber={0}";

            pgr.PageURLFormat = pageUrl;
            pgr.ShowFirstLast = true;
            pgr.PageSize = config.PageSize;
            pgr.PageCount = totalPages;
            pgr.CurrentIndex = pageNumber;
            pgr.Visible = (totalPages > 1) && config.UsePaging;
        }

        protected virtual void PopulateLabels()
        {
            EditAltText = SwirlingQuestionResource.EditLink;
            FeedBackLabel = SwirlingQuestionResource.FeedbackLabel;
            pnlPostQuestion.Visible = config.UsePostQuestionInListSetting;
            if (config.UsePostQuestionInListSetting)
            {
                btnPostQuestion.Text = SwirlingQuestionResource.AddQuestionLabel;
                btnPostQuestion.PostBackUrl = SiteRoot
                                              + "/SwirlingQuestion/PostQuestion.aspx?pageid=" +
                                              PageId.ToInvariantString()
                                              + "&mid=" + ModuleId.ToInvariantString();
            }
            mojoBasePage mojoBasePage = Page as mojoBasePage;
            if (mojoBasePage != null)
            {
                if (!mojoBasePage.UseTextLinksForFeatureSettings)
                {
                    EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
                }

                if (mojoBasePage.AnalyticsSection.Length == 0)
                {
                    mojoBasePage.AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsBlogSection", "blog");
                }
            }

        }

        protected string FormatPostAuthor(string authorName)
        {
            if (config.ShowQuestionAuthor)
            {
                return string.Format(CultureInfo.InvariantCulture, SwirlingQuestionResource.QuestionAuthorFormat, authorName);
            }
            return string.Empty;
        }

        protected string FormatAnswer(string blogHtml, string excerpt, string url, string guid)
        {
            if (config.UseExcerpt)
            {
                if ((excerpt.Length > 0) && (excerpt != "<p>&#160;</p>"))
                {
                    return excerpt + config.ExcerptSuffix + " <a href='" + FormatQuestionUrl(url, guid) + "' class='morelink'>" + config.MoreLinkText + "</a><div>&nbsp;</div>";
                }

                if (blogHtml.Length > config.ExcerptLength)
                {

                    string result = UIHelper.CreateExcerpt(blogHtml, config.ExcerptLength, config.ExcerptSuffix);
                    result += " <div class='morelink-wrapper'><div class='l'></div><div class='m'><a href='" + FormatQuestionUrl(url, guid) + "' class='morelink'>" + config.MoreLinkText + "</a></div><div class='r'></div></div><div class='clear'></div>";
                    return result;
                }

            }

            return blogHtml;
        }

        protected string FormatBlogDate(DateTime startDate)
        {
            if (timeZone != null)
            {
                return TimeZoneInfo.ConvertTimeFromUtc(startDate, timeZone).ToString(config.DateTimeFormat);
            }
            return startDate.AddHours(TimeOffset).ToString(config.DateTimeFormat);
        }

        protected string FormatQuestionUrl(string itemUrl, string guid)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/SwirlingQuestion/ViewAnswer.aspx?pageid=" + PageId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString()
                + "&item=" + guid;
        }

        protected string FormatBlogTitle(string title, int maxChars)
        {
            if (title.Length > maxChars)
            {
                title = title.Remove(maxChars);
                title += "...";
            }
            return title;
        }

        protected string FormatTooltip(string title, string content)
        {
            string result = string.Empty;
        //    if (config.UseTooltipSettings)
        //    {
        //        if (content.Length > config.TooltipMaxCharSettings)
        //        {
        //            content = UIHelper.CreateExcerpt(content, config.TooltipMaxCharSettings, "...");
        //        }
        //        result = "<div class='tooltip'><div class='title-l'></div><div class='title-m'>" + title + "</div><div class='title-r'></div><div class='body'>" + content + "</div></div>";
        //    }
        //    else
        //    {
        //        result = title;
        //    }
            return result;
        }

        private void SetJQueryScript()
        {
            //if (config.AutoScrollSetting || config.UseTooltipSettings)
            //{
            //    ltrScript.Text = "<script src='/ClientScript/jqmojo/jquery.tools.min.js' type='text/javascript'></script>";
            //    ltrAutoScrollCssSetup.Text = string.Empty;
            //}
            //if (config.AutoScrollSetting)
            //{
            //    if (config.AutoScrollVerticalSetting)
            //    {
            //        ltrAutoScrollCssSetup.Text += "<style type='text/css'>"
            //            + ".scrollable" + ModuleId + "{"
            //            + "position:relative; overflow:hidden; float:left;"
            //            + "width:" + config.AutoScrollWidthWrapperSetting + ";"
            //            + "height:" + config.AutoScrollHeightWrapperSetting + ";}"
            //            + ".scrollable" + ModuleId + " .items{"
            //            + "height:20000em; position:absolute;}"
            //            + "</style>";
            //    }
            //    else
            //    {
            //        ltrAutoScrollCssSetup.Text += "<style type='text/css'>"
            //            + ".scrollable" + ModuleId + "{"
            //            + "position:relative; overflow:hidden; float:left;"
            //            + "width:" + config.AutoScrollWidthWrapperSetting + ";"
            //            + "height:" + config.AutoScrollHeightWrapperSetting + ";}"
            //            + ".scrollable" + ModuleId + " .items{"
            //            + "width:20000em; position:absolute;}"
            //            + ".scrollable" + ModuleId + " .items div{"
            //            + "float: left;}"
            //            + "</style>";
            //    }
            //    pnlScrollable.CssClass = "scrollable" + ModuleId.ToString();
            //    ltrScript.Text += "<script type='text/javascript'>$(document).ready(function(){"
            //                        + "$('.scrollable" + ModuleId.ToString() + "').scrollable({"
            //                        + "circular: " + config.AutoScrollCircularSetting.ToString().ToLower()
            //                        + ", easing: '" + config.AutoScrollEasingSetting.ToString() + "'"
            //                        + ", steps: " + config.AutoScrollItemsSetting.ToString()
            //                        + ", speed: " + config.AutoScrollSpeedSetting.ToString()
            //                        + ", vertical: " + config.AutoScrollVerticalSetting.ToString().ToLower()
            //                        + "}).autoscroll(" + config.AutoScrollTimeSetting.ToString() + ");});</script>";
            //}
            //if (config.UseTooltipSettings)
            //{

            //    ltrScript.Text += "<script type='text/javascript'>$(document).ready(function(){"
            //                        + "$('." + config.OtherArticlesCssClass + " > div > div > a[title]').tooltip({"
            //                        + "opacity: 1"
            //                        + ", effect: '" + config.TooltipEffectSettings + "'"
            //                        + ", delay: '" + config.TooltipDelaySettings + "'"
            //                        + ", tipClass: '" + config.UseTooltipCssSettings + "'"
            //                        + "}).dynamic({ bottom: { direction: 'down', bounce: true } });;});</script>";
            //}
        }



        protected virtual void LoadSettings()
        {

            gvOthersArticle.PageSize = config.OthersPageSize;
            gvOthersArticle.AllowPaging = config.OthersUsePaging;
            
            CacheHelper.GetCurrentSiteSettings();
            TimeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            GmapApiKey = SiteUtils.GetGmapApiKey();
            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", pageNumber);

            if (Page is mojoBasePage)
            {
                basePage = Page as mojoBasePage;
                basePage.GetModule(moduleId);
            }
            //EnableContentRating = config.EnableContentRating;
            //if (config.UseExcerpt) { EnableContentRating = false; }

            //if (config.AllowComments)
            //{
            //    if (IntenseDebateAccountId.Length > 0)
            //    {
            //        ShowCommentCounts = false;
            //    }
            //}
        }
    }
}